from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from rest_framework.validators import ValidationError

import re
from .models import *

class UserSer(ModelSerializer):
    role = serializers.PrimaryKeyRelatedField(queryset=RoleModel.objects.all())
    name = serializers.SerializerMethodField()
    rank = serializers.PrimaryKeyRelatedField(queryset=RankModel.objects.all())
    r_name = serializers.SerializerMethodField()
    jobs = serializers.PrimaryKeyRelatedField(queryset=JobsModel.objects.all())
    j_name = serializers.SerializerMethodField()
    department = serializers.PrimaryKeyRelatedField(queryset=DepartmentModel.objects.all())
    d_name = serializers.SerializerMethodField()


    def get_r_name(self, obj):
        return obj.role.name

    def get_name(self, obj):
        return obj.rank.r_name

    def get_j_name(self, obj):
        return obj.jobs.j_name

    def get_d_name(self, obj):
        return obj.department.d_name
    class Meta:
        model =UserModel
        exclude=('password',)

    def validate(self, attrs):
        username = attrs.get("username")
        phone = attrs.get("phone")

        if not re.findall(r"[\u4e00-\u9fa5]{1,9}", username):
            raise ValidationError(f'{username}姓名由2到9为汉字组成')

        if not re.findall(r"^1[3-9]\d{9}$", phone):
            raise ValidationError(f"{phone}格式不正确")

        return attrs



# 菜单管理
class MenuSer(ModelSerializer):
    class Meta:
        model = MenuModel
        fields = '__all__'


# 登录日志
class LoginLogSer(ModelSerializer):
    class Meta:
        model = LoginLogModel
        fields = '__all__'

# 操作日志
class OperationLogSer(ModelSerializer):
    class Meta:
        model = OperationLogModel
        fields = '__all__'

